package model

import (
	"fmt"
	"tem/dto/common"
	"tem/dto/modelDto"
	"tem/global"
)

// Instant 文章模型
type Instant struct {
	common.IDModel `gorm:embedded`
	UserId         uint   `json:"userId" gorm:"column:user_id" validator:"required" name:"用户id"` //用户id
	Title          string `json:"title" gorm:"column:title" name:"标题"`                           //标题
	Context        string `json:"context" gorm:"column:context"  validator:"required" name:"内容"` //内容
	Image          string `json:"image" gorm:"column:image" name:"图片"`                           //图片
}

func (Instant) TableName() string {
	return "instant"
}
func (Instant) Create(i Instant) {
	fmt.Printf("%#v", i)
	global.DB.Create(&i)
}

func (Instant) GetAllList(id int, pageIndex int, pageSize int) ([]modelDto.InstantResponse, int64, error) {
	var instantList []modelDto.InstantResponse
	var count int64
	str := fmt.Sprintf("(select count(1) as cnt from likeTable where likeTable.instant_id = instant.id and likeTable.user_id = %d) as flag,", uint(id))
	//str := "(select count(1) as cnt from likeTable where likeTable.instant_id = instant.id) as likeNum,"
	err := global.DB.Table("instant").
		Select("instant.id as id," +
			"instant.context as context," +
			"instant.created_at as created_at," +
			"instant.user_id as user_id," +
			"instant.title as title," +
			"user.username as username," +
			"user.img as img," +
			str +
			"(select count(1) as cnt from likeTable where likeTable.instant_id = instant.id) as likeNum," +
			"(select count(1) as cnt from comment where comment.instant_id = instant.id) as commentNum").
		Joins("left join user on user.id = instant.user_id").
		Order("instant.created_at desc").Count(&count).Limit(pageSize).Offset((pageIndex - 1) * pageSize).
		Scan(&instantList).Error
	if err != nil {
		return nil, 0, err
	}
	return instantList, count, nil
}

func (Instant) GetListById(id uint, userId uint) (modelDto.InstantResponse, error) {
	var instantList modelDto.InstantResponse
	str := fmt.Sprintf("(select count(1) as cnt from likeTable where likeTable.instant_id = instant.id and likeTable.user_id = %d) as flag,", userId)
	err := global.DB.Table("instant").
		Where("instant.id = ?", id).
		Select("instant.id as id," +
			"instant.context as context," +
			"instant.created_at as created_at," +
			"instant.user_id as user_id," +
			"instant.title as title," +
			"user.username as username," +
			str +
			"(select count(1) as cnt from likeTable where likeTable.instant_id = instant.id) as likeNum," +
			"(select count(1) as cnt from comment where comment.instant_id = instant.id) as commentNum," +
			"user.img as img").
		Joins("left join user on user.id = instant.user_id").
		Scan(&instantList).Error
	if err != nil {
		return instantList, err
	} else {
		return instantList, nil
	}
}
